<script setup lang="ts">
import RoomStatus from './components/room-status.vue'
import RoomMessage from './components/room-message.vue'
import RoomAction from './components/room-action.vue'
// 导入io
import { io } from 'socket.io-client'
import { useUser } from '@/stores'
import { useRoute } from 'vue-router'
import { onBeforeUnmount } from 'vue'
import type { chatMsgListApi, Message, patientConsultOrderDetailApi } from '@/types/room'
import { MsgType } from '@/enums/index'
import { ref } from 'vue'
import { patientConsultOrderDetail } from '@/api/room'
import { nextTick } from 'vue'
import dayjs from 'dayjs'
import { showToast } from 'vant'

const store = useUser()
const route = useRoute()
// 连接
const socket = io(import.meta.env.VITE_APP_URL, {
  auth: {
    token: `Bearer ${store.userInfo?.token}`
  },
  query: {
    orderId: route.query.orderId as string
  }
})
// 判断是否连接成功
socket.on('connect', () => {
  console.log('连接成功')
})
socket.on('disconnect', () => {
  console.log('关闭连接')
})
// 接收第一次打开时聊天信息
const list = ref<Message[]>([])
socket.on('chatMsgList', (res: chatMsgListApi) => {
  const arr: Message[] = []
  res.data.forEach((item, index) => {
    if (index === 0) {
      time = item.createTime
    }
    arr.push({
      id: item.orderId,
      msgType: MsgType.Notify,
      msg: {
        content: item.createTime
      },
      orderId: item.orderId,
      createTime: item.createTime
    })
    arr.push(...item.items)
  })
  list.value.unshift(...arr)
  loading.value = false
  if (res.data.length === 0) {
    showToast('没更多数据了！')
  }
  if (ifFirst) {
    ifFirst = false
    nextTick(() => {
      window.scrollTo(0, document.body.scrollHeight)
    })
  }
  console.log('信息', res)
})

/*
状态变化 ：
1：加入监听事件知道状态变化
2：调用接口获取当前详情状态
*/
const orderInfo = ref<patientConsultOrderDetailApi>()
socket.on('statusChange', res => {
  getOrderInfo()
  console.log('状态变化 了', res)
})

const getOrderInfo = async () => {
  const res = await patientConsultOrderDetail(route.query.orderId as string)
  orderInfo.value = res.data
  console.log('订单详情', res)
}
getOrderInfo()

// 接收信息
socket.on('receiveChatMsg', res => {
  list.value.push(res)
  // 渲染完成再滚动滚动条
  nextTick(() => {
    window.scrollTo(0, document.body.scrollHeight)
  })
  console.log('接收 信息', res)
})

// 发送消息
const sendMessage = (txt: string) => {
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderInfo.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: txt
    }
  })
}
// 发送图片信息
const sendImage = (image: { id: string; url: string }) => {
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderInfo.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: image
    }
  })
}

// 下拉加载更多
const loading = ref(false)
let time = dayjs().format('YYYY-MM-DD')
let ifFirst = true
const refresh = () => {
  socket.emit('getChatMsgList', 20, time, route.query.orderId)
}

// 跳转该页面关闭连接
onBeforeUnmount(() => {
  // 关闭连接
  socket.close()
})
</script>

<template>
  <div class="room-page" v-if="orderInfo">
    <cp-nav-bar title="问诊室" />
    <room-status :orderInfo="orderInfo" />
    <van-pull-refresh v-model="loading" @refresh="refresh">
      <room-message :list="list" />
    </van-pull-refresh>
    <room-action @sendImage="sendImage" @sendMessage="sendMessage" :status="orderInfo.status" />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
